package org.su.generalmvc.scheduler;

import com.sun.jmx.snmp.tasks.Task;
import org.su.generalmvc.annotaion.Transaction;
import org.su.generalmvc.core.LifeCycle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 包装定时器任务
 * 
 * @author xkliu
 * 
 */
public class SchedulerTask implements Task {
	protected static final Log logger = LogFactory
			.getLog(SchedulerTask.class);

	protected Object controller;
	protected Method method;
	
	// 防止定时器重入调用
	private Lock lock = new ReentrantLock();

	// 事务级别
	protected int transLevel = -1;

	public SchedulerTask(Object controller, Method method) {
		this.controller = controller;
		this.method = method;
		transLevel = getTransLevel(method);
	}

	private int getTransLevel(Method method) {
		int transLevel = -1;
		// 确定事物级别
		Class<?>[] parameterTypes = method.getParameterTypes();
		if (parameterTypes.length > 0) {
			transLevel = 0;
			Transaction transaction = method.getAnnotation(Transaction.class);
			if (null != transaction) {
				transLevel = transaction.value();
			}
		}

		return transLevel;
	}

	@Override
	public void run() {
		if (lock.tryLock()) {
			try {
				LifeCycle.invoke(controller, method, transLevel);
			} catch (InvocationTargetException e) {
				if (e.getCause() != null) {
					logger.error(e.getCause().getMessage(), e.getCause());
				} else {
					logger.error(e.getMessage(), e);
				}
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			} finally {
				lock.unlock();
			}
		}
	}

	@Override
	public void cancel() {
	}
}
